package com.winbomb.simulife.util;

import java.util.Random;

/**
 * 概率工具类
 * 
 * @author winbomb
 * 
 */
public class ProbUtil {

	private static final int MAX_NUMBER = 100000;

	private static Random rand = new Random();

	/**
	 * 测试某个概率的事件是否会发生
	 * 
	 * @param prob
	 *            待测试的概率
	 * @return
	 */
	public static boolean test(float prob) {
		if (prob >= 1.0f) {
			return true;
		}

		if (prob <= 0.0f) {
			return false;
		}

		int num = rand.nextInt(MAX_NUMBER);

		return num < prob * MAX_NUMBER;

	}

	/**
	 * 测试概率
	 * 
	 * @param probs
	 * @return
	 */
	public static int testProbs(float[] probs) throws ProbInvalidException {

		if (probs == null || probs.length == 0) {
			throw new ProbInvalidException("Probability array is null.");
		}

		float total = 0f;
		for (int i = 0; i < probs.length; i++) {
			total += probs[i];
		}

		if (total >= 1.0001 || total <= 0.9999) {
			throw new ProbInvalidException("Total probability is not 1.0 ");
		}

		int num = rand.nextInt(MAX_NUMBER);
		float prob = 0f;
		int i = 0;
		for (; i < probs.length; i++) {
			prob += probs[i];

			if (num <= MAX_NUMBER * prob) {
				break;
			}
		}

		return i;
	}
}
